package web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
import sevice.ServiceDAOFactory;
import sevice.UserService;
import util.Md5Code;

@WebServlet("/user/login.do")
public class LoginServlet extends HttpServlet {
	public static final String AC = "0";
	public static final String BO = "1";
	private static final long serialVersionUID = 7845020365782809722L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method != null) {
			switch (method) {
			case LoginServlet.AC:
				req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
				break;
			case LoginServlet.BO:
				try {
					login(req, resp);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		}

	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		UserService userService = ServiceDAOFactory.getUserDAO();
		User user = userService.findByEmail(req.getParameter("email"));
		if (user == null || !user.getPassword().equals(Md5Code.createMd5Code(req.getParameter("password")))) {
			req.setAttribute("login_err", "账号密码错误");
			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
			return;
		}
		user.setLastLoginIp(req.getRemoteAddr());
		
		user.setLastLoginTime(System.currentTimeMillis());
		userService.update(user);
		req.getSession().setAttribute("s_user", user);
//		if (!user.isEmailVerify()) {
//			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
//			return;
//		}

		
		resp.sendRedirect(req.getContextPath() + "/main.do");

	}
}
